<template>
    <view class="store-page">
        <scroll-view scroll-y="true" class="content-box">

            <uni-forms :rules="rules" :value="form" ref="form" validate-trigger="bind" err-show-type="undertext"
                label-width="400rpx">

                <view class="basic-information">
                    <uni-forms-item label="公司名称" label-width="200rpx" name="companyName">
                        <input type="text" v-model="form.companyName" placeholder="请填写" />
                    </uni-forms-item>

                    <uni-forms-item label="手机号" label-width="200rpx" name="phone">
                        <input type="text" v-model="form.phone" placeholder="请填写" />
                    </uni-forms-item>

                    <uni-forms-item label="联系人" label-width="200rpx" name="linkmanName">
                        <input type="text" v-model="form.linkmanName" placeholder="请填写" />
                    </uni-forms-item>

                    <uni-forms-item label="地址" label-width="200rpx" name="legalPersonName">
                        <view class="flex-reverse" @click="changeRegionString">
                            <view class="selct-placeholder" v-if="form.vehicleLocation == ''">请选择</view>
                            <view v-else>
                                {{ form.vehicleLocation }}
                            </view>
                            <u-icon name="arrow-right"></u-icon>
                        </view>
                    </uni-forms-item>
                    <view class="information-upload">

                        <uni-forms-item>
                            <template slot="label">
                                <view class="formTitle-item">经营执照</view>
                            </template>
                            <view class="imgs imgs-more">
                                <u-upload :fileList="fileImage.operationSitePhotos" @afterRead="afterRead"
                                    @delete="deletePic" name="operationSitePhotos" multiple :maxCount="1"
                                    :previewFullImage="false" width="200rpx" height="200rpx"
                                    :deletable="isApproved != 2"></u-upload>
                            </view>
                        </uni-forms-item>
                    </view>

                </view>


            </uni-forms>
        </scroll-view>
        <you-bottom-btn :btnConfig="bottomBtnConfig" v-if="isApproved != 2" @clickSubmit="clickSubmit"></you-bottom-btn>
        <u-datetime-picker :show="isShowTime" mode="date" ref="datetimePicker" :minDate="Number(new Date())"
            v-model="timeValue" @cancel="isShowTime = false" @confirm="selectTimeConfirm"></u-datetime-picker>
        <u-popup :show="isSelectShow" :round="12" mode="bottom" @close="isSelectShow = false">
            <view class="select-cotent">
                <view class="select-list">
                    <view class="select-item" v-for="(item, index) in options" @click="selectItem(item)">
                        {{ item.name }}
                    </view>
                </view>
                <view class="select-item" @click="isSelectShow = false">
                    取消
                </view>
            </view>
        </u-popup>

        <liu-choose-address ref="scroll" @change='chooseSuccess' :key="isAddress"></liu-choose-address>

    </view>
</template>

<script>
import zlxlsUploadImg from "@/components/zlxls-upload-img/zlxls-upload-img.vue"
import {
    baseUrl,
    baseImgUrl
} from '@/config'
import pageConfig from '@/config'
import { timestampToDate, forrmatterEnmu } from '@/utils/index.js'

import settleIn from '@/api/settleIn.js'
import { getToken, removeToken } from '@/utils/auth'
import { showConfirm } from '@/utils/common'
export default {
    name: 'Store',
    components: { zlxlsUploadImg },
    data() {
        return {
            isShowTime: '',
            titleEntrn: "汽车销售入驻",
            uploadUrl: baseUrl + "/common/upload",
            sexs: [{
                text: '上架',
                value: 1
            }, {
                text: '下架',
                value: 2
            }],
            form: {
                id: '',  //id
                userId: '',  //用户id
                companyName: '',//公司名称
                phone: '',//手机号
                linkmanName: '',//联系人
                businessLicense: '',//营业执照
                vehicleLocation: '',
                timeOfApplication: '',//申请时间
                auditStatus: '',//审核状态 1通过 2拍绝
                auditTime: '',//审核时间
                auditName: '',//审核人
                province: '',//省code
                city: '',//省code
            },
            fileImage: {
                businessLicense: [],
                roadTransportPermit: [],
                legalPersonIdCardFront: [],
                legalPersonIdCardBack: [],
                businessLeaderIdCardFront: [],
                businessLeaderIdCardBack: [],
                operationSitePhotos: [],
            },
            header: {
                'Authorization': 'Bearer ' + getToken()
            },
            params: {
                cover: '',
                slider: '',
            },
            entryType: 1,
            imageValue: '',
            rules: {
                iphone: {
                    rules: [{
                        required: true,
                        errorMessage: '请填写电话',
                    },
                    {
                        minLength: 11,
                        maxLength: 11,
                        errorMessage: '请填写正确电话长度',
                    }
                    ],
                },
            },
            bottomBtnConfig: [{
                text: '确认',
                class: 'confirm',
                funcName: 'clickSubmit'
            }],
            isSelectShow: false,
            options: [],
            cityObject: {
                province: '',
                provinceString: '',
                city: '',
                cityString: '',
                region: '',
                regionString: '',
                aimProvince: '',
                aimProvinceString: '',
                aimCity: '',
                aimCityString: '',
                aimRegion: '',
                aimRegionString: ''
            },
            isApproved: 0,
            isAddress: true,
            sitePhotosMaxCount: 6
        }
    },

    async onLoad(e) {

        uni.setNavigationBarTitle({
            title: this.titleEntrn
        });


    },
    async onShow() {

    },
    mounted() {
        const systemInfo = uni.getSystemInfoSync();
    },
    methods: {
        // 新增图片
        async afterRead(event) {
            console.log(event,'eeeeee')
            // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
            let lists = [].concat(event.file);
            let fileListLen = this.fileImage[`${event.name}`].length;
            lists.map((item) => {
                this.fileImage[`${event.name}`].push({
                    ...item,
                    status: 'uploading',
                    message: '上传中'
                })
            })
            for (let i = 0; i < lists.length; i++) {
                try {
                    const result = await this.uploadFilePromise(lists[i].url)
                    // 返回给后端服务器的 结果需要赋值给 
                    this.form.businessLicense = result.url
                    console.log(result, '上传图像result11111111');
                    let item = this.fileImage[`${event.name}`][fileListLen];
                    this.fileImage[`${event.name}`].splice(fileListLen, 1, Object.assign(item, {
                        status: result.code,
                        message: result.code != '200' ? '上传失败' : '上传成功',
                        url: result.fileName
                    }))
                    fileListLen++
                } catch (e) {
                    //TODO handle the exception
                    this.fileImage[`${event.name}`].splice(fileListLen, 1)
                }

            }
            console.log(this.fileImage)
        },
        uploadFilePromise(url, index) {
            return new Promise((resolve, reject) => {
                let a = uni.uploadFile({
                    url: baseUrl + '/common/upload', // 仅为示例，非真实的接口地址
                    filePath: url,
                    name: 'file',
                    header: {
                        'Authorization': 'Bearer ' + getToken()
                    },
                    formData: {},
                    success: (respose) => {
                        let res = respose.data && JSON.parse(respose.data);
                        console.log(res, "resresresres")
                        if (res.code == 401) {
                            showConfirm('登录状态已过期，您可以继续留在该页面，或者重新登录?').then(reslv => {
                                if (reslv.confirm) {
                                    removeToken()
                                    uni.reLaunch({ url: '/subPages/login/index' })
                                }
                            })
                        } else if (res.code == 200) {
                            setTimeout(() => {
                                resolve(res)
                            }, 1000)
                        } else {
                            uni.showToast({
                                icon: 'none',
                                title: '上传失败，请稍后再试'
                            })
                            reject("err")
                        }

                    },
                    fail: (err) => {
                        console.log(err, "err");

                    }
                });
            })
        },

        changeRegionString() {
            this.isAddress = !this.isAddress
            this.type = 1
            this.$refs.scroll.open()
        },

        //地址选择成功
        chooseSuccess(e) {
            if (this.type == 1) {
                this.form.province = e.value[0].value
                this.form.city = e.value[1].value
                this.form.vehicleLocation = e.value[0].label + e.value[1].label

            }
        },

        selectTime(flag) {
            // 1、托运时间 2、截止时间
            this.isShowTime = true;
            this.selectTimeFlag = flag;
            this.timeValue = Number(new Date())
            if (this.form.lock_for_time && this.form.lock_for_time != '') {
                this.timeValue = Number(new Date(this.form.lock_for_time.replace(/-/g, '/')));
            }



        },
        selectTimeConfirm(e) {
            console.log(this.timeValue)
            let time = timestampToDate(e.value, 'ymd');
            console.log(time, 'eeee')
            this.form.lock_for_time = time;
            this.isShowTime = false;
        },



        selectEntry(e) {
            if (e == 1) {
                this.options = [
                    {
                        name: '新车',
                        value: '1',
                    },
                    {
                        name: '二手车',
                        value: '2',
                    },
                    {
                        name: '新能源',
                        value: '3',
                    },
                ]
            }
            this.isSelectShow = true;
        },
        selectItem(item) {
            this.form.vehicle_type = item.value
            this.form.vehicle_name = item.name
            this.isSelectShow = false;
        },
        select(e) {
        },
        async clickSubmit() {
            console.log('始发地', this.form)
            // this.form.businessLicense = this.fileImage.operationSitePhotos[0]
            // this.form.businessLicense = this.fileImage.operationSitePhotos[0]
            this.form.userId = uni.getStorageSync('userId')
            if (this.form.companyName == '') {
                uni.showToast({
                    title: "请填写公司名称",
                    icon: "none"
                })
                return;
            }

            if (this.form.phone == '') {
                uni.showToast({
                    title: "请填写手机号",
                    icon: "none"
                })
                return;
            }


            if (this.form.linkmanName == '') {
                uni.showToast({
                    title: "请填写联系人",
                    icon: "none"
                })
                return;
            }


            if (this.form.vehicleLocation == '') {
                uni.showToast({
                    title: "请选择地址",
                    icon: "none"
                })
                return;
            }

            if (this.form.businessLicense == '') {
                uni.showToast({
                    title: "请上传经营执照",
                    icon: "none"
                })
                return;
            }
            let res = await settleIn.save({ ...this.form });
            if (res.code == 200) {
                uni.showToast({
                    title: "操作成功",
                    icon: 'none'
                });
                setTimeout(() => {
                    uni.switchTab({
                        url: '/pages/settleIn'
                    })
                }, 1000)
            }
        },
        deletePic(event) {
            this.fileImage[`${event.name}`].splice(event.index, 1);
            console.log(this.fileImage[`${event.name}`])
        },
    }
}
</script>
<style lang="scss" scoped>
/deep/.u-upload__wrap__preview {
    margin: 0;
}

.imgs-more {
    /deep/.u-upload__wrap__preview {
        margin-right: 10rpx;
        margin-bottom: 10rpx;
    }
}

.select-cotent {
    font-size: 34rpx;
    color: #161823;
    background: #f3f3f3;
    overflow: hidden;
    border-radius: 12rpx 12rpx 0 0;

    .select-list {
        margin-bottom: 16rpx;
        background: #fff;
        max-height: 40vh;
        overflow-y: auto;
    }

    .select-item {
        padding: 32rpx;
        text-align: center;
        background: #fff;
    }
}

.store-page {
    background: #f6f6f6;

    .content-box {
        padding: 0 28rpx;
        padding-bottom: 220rpx;
        height: 100vh;
        margin-top: 20rpx;

        .formTitle {
            font-weight: 500;
            color: #1a1a1a;
            margin: 20rpx 0;
            font-size: 28rpx;

            text {
                color: red;
            }
        }

        .formTitle-item {
            font-weight: 500;
            color: #666;
            font-size: 28rpx;
            margin-bottom: 10rpx;
            margin-top: 30rpx;
        }

        .basic-information,
        .information-upload {
            background: #fff;
            padding: 10rpx 24rpx;
            border-radius: 10rpx;
        }

        .basic-information {
            input {
                height: 100rpx;
                font-size: 28rpx;
                text-align: right;
            }
        }
    }
}

.information-upload {
    .uni-forms-item {
        display: block;

    }
}

.selct-placeholder {
    color: #999;
    font-size: 28rpx;
    text-align: right;
}

.flex-reverse {
    height: 100%;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    line-height: 1;
}
</style>
<style lang="scss">
.basic-information {

    .uni-group__content,
    .information-upload {
        border-radius: 20rpx !important;

    }

    .uni-forms-item__label {
        width: 250rpx !important;
    }

    .uni-forms-item {
        align-items: center;
        margin: 0;
        border-bottom: 1px solid #e9e9e9;

        &:last-child {
            border: 0;
        }
    }
}

.information-upload {
    .uni-forms-item {
        display: block;

    }
}

.imgs {
    display: flex;
    justify-content: space-between;

    .imgs-item {
        width: 312rpx;
        background: #F6F6F6;
        padding: 30rpx 20rpx;
        padding-bottom: 16rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        border-radius: 8rpx;
        flex: 1;

        &:nth-child(2n + 1) {
            margin-right: 20rpx;
        }

        >text {
            color: #222;
            font-size: 24rpx;
            line-height: 1;
            padding-top: 16rpx;
        }

        image {
            width: 240rpx;
            height: 170rpx;
        }
    }
}

.msg--active {
    opacity: 1;
    transform: translateY(-100%);
}

.checkbox {
    margin-left: 170rpx;

    .uni-data-checklist .checklist-group .checklist-box {
        margin-right: 0rpx;
        margin-left: 12rpx;
    }
}
</style>